//
//  VideoViewController.m
//  Otaku
//
//  Created by lanou3g on 16/5/5.
//  Copyright © 2016年 Liuwx. All rights reserved.
//

#import "VideoViewController.h"
#import "LWX_VideoCell.h"
#import "LWX_VideoModel.h"
#import "VideoPlayView.h"

#import "VideoCommentController.h"
@interface VideoViewController ()<UITableViewDataSource,UITableViewDelegate,VideoPlayViewDelegate,VideoTableViewCellDelegate,UMSocialUIDelegate>
@property (nonatomic, strong) NSMutableArray *videoArray;
@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) VideoPlayView *playView;
@property (nonatomic, strong) LWX_VideoCell *currentSelectedCell;
@property (nonatomic, assign) BOOL isFullScreenPlaying;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) LWX_VideoModel *shareModel;
@end
static NSString *const reuseID = @"cell";
@implementation VideoViewController

- (void)dealloc {
    [self.myTableView removeObserver:[self.myTableView defaultHeader] forKeyPath:@"contentOffset"];
    
}

- (NSMutableArray *)videoArray {
    if (!_videoArray) {
        self.videoArray = [NSMutableArray new];
    }
    return _videoArray;
}

- (UITableView *)myTableView {
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, FUll_VIEW_WIDTH, FUll_CONTENT_HEIGHT - PageBtn) style:UITableViewStylePlain];
    }
    return _myTableView;
}


- (void)viewDidLoad {
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.view addSubview:self.myTableView];
    self.videoArray = [NSMutableArray new];
    [self loadData];
    [self setupBasic];
    [self setupTableView];
    
    __weak typeof(self) weakSelf = self;
    
    [self.myTableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        [weakSelf.videoArray removeAllObjects];
        [weakSelf.myTableView reloadData];
        [weakSelf loadData];
    }];
    
    
    
self.navigationController.navigationBar.translucent = NO;
}

- (void)loadData {
    [LWXNetWorkRequestManager requestURL:[NSURL URLWithString:VIDEO_URL] Method:LWX_GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSDictionary *dataDic = jsonDict[@"data"];
            for (NSDictionary *itemDict in dataDic[@"data"]) {
                LWX_VideoModel *model = [[LWX_VideoModel alloc]init];
               
                [model setValuesForKeysWithDictionary:itemDict];
                if (model.mp4_url.length > 0) {
                    [self.videoArray addObject:model];
                }

            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.myTableView reloadData];
                [[self.myTableView defaultHeader] endRefreshing];
                
            });
        }
 
    }];
}

- (void)setupTableView {
    self.view.backgroundColor = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:1.0];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.myTableView.scrollIndicatorInsets = self.myTableView.contentInset;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.myTableView registerNib:[UINib nibWithNibName:NSStringFromClass([LWX_VideoCell class]) bundle:nil] forCellReuseIdentifier:reuseID];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    if (self.isFullScreenPlaying == NO) {
        [self.playView resetPlayView];
        
    }
   self.navigationController.navigationBar.alpha = 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.videoArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    LWX_VideoModel *model = self.videoArray[indexPath.row];
    return model.cellHeight;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LWX_VideoCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseID];
    [cell.shareBtn addTarget:self action:@selector(shareBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.indexPath = indexPath;
    cell.delegate = self;
    cell.model = self.videoArray[indexPath.row];
    self.shareModel = self.videoArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self pushToVideoCommentViewControllerWithIndexPath:indexPath];
    
}

- (void)pushToVideoCommentViewControllerWithIndexPath:(NSIndexPath *)indexPath {
    
    VideoCommentController *VCC = [[VideoCommentController alloc]init];
    
    VCC.index = indexPath.row;
    VCC.videoArray = self.videoArray;
    VCC.model = self.videoArray[indexPath.row];
    
    LWX_VideoModel *model = self.videoArray[indexPath.row];
    
    VCC.videoTitle = model.text;
    VCC.groupID = model.group_id;
    VCC.cellHeight = model.cellHeight;
    UINavigationController *naVC = [[UINavigationController alloc]initWithRootViewController:VCC];
    [self presentViewController:naVC animated:YES completion:nil];

}


- (void)clickRedButton:(NSIndexPath *)indexPath {
   [self pushToVideoCommentViewControllerWithIndexPath:indexPath];
}

// 分享事件
- (void)shareBtnAction:(UIButton *)btn {
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"572c6a8ce0f55ac72d000352"
                                      shareText:@"分享的文字"
                                     shareImage:[UIImage imageNamed:@"icon"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,nil]
                                       delegate:self];
    [UMSocialData defaultData].extConfig.title = self.shareModel.text;
    [UMSocialData defaultData].shareText = [NSString stringWithFormat:@"%@+%@",self.shareModel.text,self.shareModel.share_url];
    
}

-(void)setupBasic {
    self.currentPage = 0;
    self.isFullScreenPlaying = NO;
}


#pragma mark VideoTableViewCell的代理方法
- (void)clickVideoButton:(NSIndexPath *)indexPath {
    
    [self.playView resetPlayView];
    LWX_VideoCell *cell = [self.myTableView cellForRowAtIndexPath:indexPath];
    self.currentSelectedCell = cell;
    VideoPlayView *playView = [VideoPlayView videoPlayView];
    LWX_VideoModel *model = self.videoArray[indexPath.row];
    playView.frame = model.videoFrame;
    [cell addSubview:playView];
    cell.playView = playView;
   self.playView = playView;
    self.playView.delegate = self;
    
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:model.mp4_url]];
    self.playView.playerItem = item;

}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.playView.superview && self.isFullScreenPlaying == NO) {//点全屏和退出的时候，也会调用scrollViewDidScroll这个方法
        NSIndexPath *indePath = [self.myTableView indexPathForCell:self.currentSelectedCell];
        if (![self.myTableView.indexPathsForVisibleRows containsObject:indePath]) {//播放video的cell已离开屏幕
            [self.playView resetPlayView];
        }
    }
 
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
